package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redstar.HappyRefresh.cache.UserInfo;
import com.redstar.HappyRefresh.mapper.FavoritesMapper;
import com.redstar.HappyRefresh.pojo.Favorites;
import com.redstar.HappyRefresh.pojo.FavoritesVideo;
import com.redstar.HappyRefresh.service.FavoritesService;
import com.redstar.HappyRefresh.service.FavoritesVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class FavoritesServiceImpl extends ServiceImpl<FavoritesMapper, Favorites> implements FavoritesService {
    @Autowired
    private FavoritesVideoService favoritesVideoService;

    @Override
    public List<Favorites>  getByUserId(Long userId) {  // 查询指定用户的收藏夹信息，加上每个收藏夹中的视频总数
        List<Favorites> favoritesList = list(new LambdaQueryWrapper<Favorites>().eq(Favorites::getUserId, userId));
        if (ObjectUtils.isEmpty(favoritesList)) {
            return favoritesList;
        }
        // 获取收藏夹id
        List<Long> idList = favoritesList.stream().map(Favorites::getId).collect(Collectors.toList());
        // 根据收藏夹id查询给收藏夹下的视频数量
        List<FavoritesVideo> favoritesVideoList = favoritesVideoService.list(new LambdaQueryWrapper<FavoritesVideo>().in(FavoritesVideo::getFavoritesId, idList));
        // 将List转化为Map，key为收藏夹id，value为改收藏夹下的视频数量
        Map<Long, Long> favoritesVideoMap = favoritesVideoList.stream().collect(Collectors.groupingBy(FavoritesVideo::getFavoritesId, Collectors.counting()));
        // 将视频数量填入收藏夹信息中
        for (Favorites f : favoritesList) {
            Long videoCount = favoritesVideoMap.getOrDefault(f.getId(), 0L);
            f.setVideoCount(videoCount);
        }
        return favoritesList;
    }

    @Override
    public String removeFavoritesAndFavoritesVideo(Long id) { // 删除当前用户的收藏夹和收藏视频表中的视频
        Long userId = UserInfo.get();
        Favorites favorites = getOne(new LambdaQueryWrapper<Favorites>().eq(Favorites::getId, id).eq(Favorites::getUserId, userId));
        if (!ObjectUtils.isEmpty(favorites)) {
            if ("默认收藏夹".equals(favorites.getName())) {
                return "你小子还想删除默认收藏夹";
            }
            remove(new LambdaQueryWrapper<Favorites>().eq(Favorites::getId, id).eq(Favorites::getUserId, userId));
            favoritesVideoService.remove(new LambdaQueryWrapper<FavoritesVideo>()
                    .eq(FavoritesVideo::getFavoritesId, id).eq(FavoritesVideo::getUserId, userId));
        } else {
            return "你小子还想删除别人的收藏夹";
        }
        return "success"; // 收藏夹删除成功
    }
}
